import { memo, useState, useEffect, useCallback } from 'react';
import type { ReactNode, FC } from 'react';
import { BackToTopWrapper } from './style';
interface IProps {
  children?: ReactNode;
}

const BackToTop: FC<IProps> = (props) => {
  const [isVisible, setIsVisible] = useState(false);

  const toggleVisibility = useCallback(() => {
    if (window.pageYOffset > 300) {
      setIsVisible(true);
    } else {
      setIsVisible(false);
    }
  }, [window.pageYOffset]);

  const scrollToTop = useCallback(() => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth',
    });
  }, []);

  useEffect(() => {
    window.addEventListener('scroll', toggleVisibility);
    return () => {
      window.removeEventListener('scroll', toggleVisibility);
    };
  }, []);

  return (
    <BackToTopWrapper>{isVisible && <button className="btns sprite" onClick={scrollToTop}></button>}</BackToTopWrapper>
  );
};

export default memo(BackToTop);
